package com.fly.snailrun.business;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.file.FileNameUtil;
import com.fly.snailrun.base.config.JianYingConfig;
import com.fly.snailrun.base.exception.BusinessErrorCodeEnum;
import com.fly.snailrun.base.exception.BusinessException;
import com.fly.snailrun.domain.dto.DraftFileGenerateDto;
import com.fly.snailrun.utils.JianYinUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.PostConstruct;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author：gaoxu
 * @date：Created in 2024/7/25 15:52
 */
@Service
public class DraftFileService {

    private static Logger log = LoggerFactory.getLogger(DraftFileService.class);

    private final static String DOU_YIN_SUFFIX_PATH = "/Users/gaoxu/Downloads/douyin";

    private final static String DOU_YIN_END_COPY_WRITER = "#小说推荐 #小说 #书荒推荐 #解压 #沉浸式助眠";

    @Autowired
    private JianYingConfig jianYingConfig;

    @Autowired
    private DraftContentHandlerService draftContentHandlerService;

    /**
     * 草稿目录
     */
    private String directoryPath;

    /**
     * 草稿模板名称
     */
    private String draftTemplateName;

    @PostConstruct
    public void init() {
        directoryPath = jianYingConfig.getDirectory();
        draftTemplateName = jianYingConfig.getName();
    }

    /**
     * 生成草稿文件
     *
     * @param draftNum          生成草稿文件个数
     * @param draftFileName     草稿文件名
     * @param draftTemplateName 草稿模板文件名
     * @return
     */
    public void createDraftFile(Integer draftNum, String draftFileName, String draftTemplateName) {
        log.info("DraftFileService createDraftFile  param:{}", draftNum);
        List<String> draftFile;
        if (StringUtils.isEmpty(draftFileName)) {
            draftFile = JianYinUtil.createDraftFile(draftNum, draftTemplateName);
        } else {
            draftFile = JianYinUtil.createDraftFile(draftNum, draftFileName, draftTemplateName);
        }
        log.info("DraftFileService createDraftFile success  result:{}", draftFile);
    }

    /**
     * 生成草稿文件
     *
     * @param draftFileGenerateDto 草稿文件生成dto
     * @param draftFileName        草稿文件名
     * @param draftTemplateName    草稿模板文件名
     */
    public void generateDraftFile(DraftFileGenerateDto draftFileGenerateDto, String draftFileName, String draftTemplateName) {
        log.info("DraftFileService generateDraftFile  param:{}", draftFileGenerateDto);
        List<String> draftFileList = new ArrayList<>();
        if (StringUtils.isEmpty(draftFileName)) {
            draftFileList = getDraftFileListByConfig(null, draftTemplateName);
        } else {
            draftFileList = getDraftFileListByConfig(draftFileName, draftTemplateName);
        }
        if (CollectionUtils.isEmpty(draftFileList)) {
            log.info("DraftFileService generateDraftFile getDraftFileListByConfig is empty!");
            return;
        }
        //按照草稿模板生成草稿文件
        draftFileList.forEach(draftFilePath -> {
            draftContentHandlerService.createDraftMovieByConfig(null, draftFilePath);
        });
    }

    /**
     * 删除生成的模板的草稿文件
     *
     * @param draftFileName     草稿文件名
     * @param draftTemplateName 草稿模板文件名
     */
    public void generateDraftFileBatchDel(String draftFileName, String draftTemplateName) {
        List<String> draftFileNameList = getDraftFilePathList(draftFileName, draftTemplateName);
        draftFileNameList.forEach(draftFilePath -> {
            FileUtil.del(draftFilePath);
        });
        log.info("DraftFileService generateDraftFileBatchDel success!");
    }

    public void generateDouyinCopywriter(String draftFileName, String draftTemplateName) {
        List<String> draftFileNameList = getDouyinCopyPathList(draftFileName, draftTemplateName);
        draftFileNameList.forEach(draftFilePath -> {
            File[] files = FileUtil.ls(draftFilePath);
            for (File file : files) {
                String fileName = FileNameUtil.getName(file);
                if (fileName.endsWith(".mp4")) {
                    FileUtil.move(new File(draftFilePath + "/" + fileName), new File(DOU_YIN_SUFFIX_PATH + "/" + fileName), true);
                }
                if (fileName.endsWith(".txt")) {
                    List<String> douyinCopywriterList = FileUtil.readUtf8Lines(new File(draftFilePath + "/" + fileName)).stream().limit(10).collect(Collectors.toList());
                    String douyinCopywriterListStr = String.join(",", douyinCopywriterList);
                    List<String> newDouyinCopywriterList = new ArrayList<>();
                    newDouyinCopywriterList.add(douyinCopywriterListStr);
                    newDouyinCopywriterList.add(DOU_YIN_END_COPY_WRITER);
                    FileUtil.writeUtf8Lines(newDouyinCopywriterList, DOU_YIN_SUFFIX_PATH + "/" + fileName);
                    FileUtil.del(new File(draftFilePath + "/" + fileName));
                }
            }
            FileUtil.del(new File(draftFilePath));
        });
    }

    public void douyinPublish() {
        String property = System.getProperty("user.dir");
        String scriptPath = property + "/sh/douyinupload.sh";
        try {
            Process process = Runtime.getRuntime().exec("/bin/bash " + scriptPath);
            BufferedReader outputReader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8"));
            String line;
            while ((line = outputReader.readLine()) != null) {
                log.info("DraftFileService douyinPublish excec result:{}", line);
            }
            process.waitFor();
        } catch (Exception e) {
            log.error("DraftFileService douyinPublish is error:{}", e);
            throw new BusinessException(BusinessErrorCodeEnum.PARAM_NULL_ERROR);
        }
    }

    private List<String> getDouyinCopyPathList(String draftFileName, String draftTemplateName) {
        String draftFilePath = DOU_YIN_SUFFIX_PATH + "/";
        File[] files = FileUtil.ls(draftFilePath);
        String filePrefix;
        if (StringUtils.isNotBlank(draftTemplateName)) {
            this.draftTemplateName = draftTemplateName;
        }
        if (StringUtils.isEmpty(draftFileName)) {
            filePrefix = this.draftTemplateName + "_snail_";
        } else {
            filePrefix = this.draftTemplateName + "_" + draftFileName + "_";
        }
        List<String> newDraftFileNameList = new ArrayList<>();
        for (File file : files) {
            String fileName = FileNameUtil.getName(file);
            if (fileName.startsWith(filePrefix)) {
                newDraftFileNameList.add(DOU_YIN_SUFFIX_PATH + "/" + fileName);
            }
        }
        return newDraftFileNameList;
    }


    /**
     * 获取剪映草稿模板文件的全路径列表
     *
     * @param draftFileName
     * @return
     */
    private List<String> getDraftFilePathList(String draftFileName, String draftTemplateName) {
        String draftFilePath = directoryPath + "/";
        File[] files = FileUtil.ls(draftFilePath);
        String filePrefix;
        if (StringUtils.isNotBlank(draftTemplateName)) {
            this.draftTemplateName = draftTemplateName;
        }
        if (StringUtils.isEmpty(draftFileName)) {
            filePrefix = this.draftTemplateName + "_snail_";
        } else {
            filePrefix = this.draftTemplateName + "_" + draftFileName + "_";
        }
        List<String> newDraftFileNameList = new ArrayList<>();
        for (File file : files) {
            String fileName = FileNameUtil.getName(file);
            if (fileName.startsWith(filePrefix)) {
                newDraftFileNameList.add(directoryPath + "/" + fileName);
            }
        }
        return newDraftFileNameList;
    }

    /**
     * 获取剪映草稿文件的文件名列表
     *
     * @param draftFileName
     * @return
     */
    private List<String> getDraftFileListByConfig(String draftFileName, String draftTemplateName) {
        String draftFilePath = directoryPath + "/";
        File[] files = FileUtil.ls(draftFilePath);
        String filePrefix;
        if (StringUtils.isNotBlank(draftTemplateName)) {
            this.draftTemplateName = draftTemplateName;
        }
        if (StringUtils.isEmpty(draftFileName)) {
            filePrefix = this.draftTemplateName + "_snail_";
        } else {
            filePrefix = this.draftTemplateName + "_" + draftFileName + "_";
        }
        List<String> newDraftFileNameList = new ArrayList<>();
        for (File file : files) {
            String fileName = FileNameUtil.getName(file);
            if (fileName.startsWith(filePrefix)) {
                newDraftFileNameList.add(fileName);
            }
        }
        return newDraftFileNameList;
    }
}